#！/bin/bash
# 打包脚本

deployFolder=deploy
dockerFolder=docker
targetFolder=target
project_tar=demo.tgz

error() {
  echo -e "\033[31m[error] $1\033[0m"
}

warning() {
  echo -e "\033[33m$1\033[0m"
}

info() {
  echo -e "\033[32m$1\033[0m"
}

# 检查命令是否存在
checkCmd() {
  info "check cmd..."
  ret=0

  if ! hash java 2>/dev/null; then
    error "java not found"
    ret=1
  fi

  if ! hash mvn 2>/dev/null; then
    error "maven not found"
    ret=1
  fi

  if [ $ret -ne 0 ]; then
    exit 1
  fi
}

mvnInstall() {
  info "mvn clean install... "

  mvn clean package

  jarName=$(basename "$(ls target/demo*.jar)")
  if [ ! -f "target/${jarName}" ]; then
    error "${jarName} not existed pwd: $(pwd)"
    exit 1
  fi
}

pack() {
  info "packing... "
  if [ ! -d ${deployFolder} ]; then
      mkdir ${deployFolder}
  fi

  cp ${targetFolder}/${jarName} ${deployFolder}
  cp ${dockerFolder}/* ${deployFolder}
  tar czf ${project_tar}  ${deployFolder}
}

clean() {
  info "cleaning... "

  if [ -d ${targetFolder} ]; then
    rm -rf ${targetFolder}
  fi
  
  if [ -d ${deployFolder} ]; then
    rm -rf ${deployFolder}
  fi

}

usage() {
  echo "Usage: $0"
  echo ""
}

checkCmd

clean

mvnInstall
pack

echo "Deploy successfully, Please check ${project_tar}"
